var express = require('express');
var router = express.Router();
var query = require('../db');
var jwt = require('jsonwebtoken');

// Token 配置
let secretOrPrivateKey = 'LCJpYXQiOjE2MjAzOTc'; // token key
let expiresIn = 60 * 60 * 24; // 过期时间

router.post('/getall', async function (req, res, next) {
  const sql = 'select u_id,u_name from user where `u_roles`="stu"';
  const rows = await query(sql);

  return res.json({
    code: 20000,
    data: rows,
  });
});

router.post('/signup', async function (req, res, next) {
  console.log(req.body);
  if (!req.body.username) {
    return res.json({
      code: 20000,
      data: {
        message: '用户名不能为空',
        type: 'warning',
      },
    });
  }
  if (!req.body.password) {
    return res.json({
      code: 20000,
      data: {
        message: '密码不能为空',
        type: 'warning',
      },
    });
  }
  if (!req.body.roles) {
    return res.json({
      code: 20000,
      data: {
        message: '权限不能为空',
        type: 'warning',
      },
    });
  }
  let sql = 'select * from user where u_name= ?';
  let rows = await query(sql, [req.body.username]);
  if (rows.length != 0) {
    return res.json({
      code: 20000,
      data: {
        message: '该用户已存在！',
        type: 'warning',
      },
    });
  }
  sql = 'INSERT INTO user(u_name, u_pw, u_roles, u_avatar)VALUES ( ?, ?, ?, ?)';
  rows = await query(sql, [req.body.username, req.body.password, req.body.roles, req.body.avatar]);
  // console.log(rows);
  return res.json({
    code: 20000,
    data: {
      message: '注册成功',
      type: 'success',
    },
  });
});

router.post('/login', async function (req, res, next) {
  const sql = 'select * from user where u_name= ? and u_pw= ?';
  const rows = await query(sql, [req.body.username, req.body.password]);

  if (rows.length === 0) return res.json({ message: '账号或密码错误！' });
  let token = jwt.sign({ u_id: rows[0].u_id }, secretOrPrivateKey, {
    expiresIn: expiresIn,
  });
  return res.json({
    code: 20000,
    data: { token: token },
  });
});

router.post('/logout', function (req, res, next) {
  return res.json({
    code: 20000,
    data: 'success',
  });
});

router.get('/info', async function (req, res, next) {
  if (!req.query.token) return res.json({ message: 'Token不存在，请重新登录！' });
  try {
    var decoded = jwt.verify(req.query.token, secretOrPrivateKey);
  } catch (err) {
    console.error('Token核对失败： invalid signature');
    return res.json({ message: 'Token过期，请重新登录！' });
  }
  console.log('Token核对成功： ', decoded);

  const sql = 'select * from user where u_id= ?';
  const rows = await query(sql, [decoded.u_id]);
  if (rows.length === 0) return res.json({ message: '用户信息不存在，请重新登录！' });
  console.log('u_roles为： ', rows[0].u_roles.split(','));
  return res.json({
    code: 20000,
    data: {
      roles: rows[0].u_roles.split(','),
      introduction: 'I am a super administrator',
      avatar: rows[0].u_avatar ? rows[0].u_avatar : 'https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif',
      name: rows[0].u_name,
    },
  });
});

module.exports = router;
